package com.xzh.wms.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.xzh.wms.dto.FileInfoDTO;
import com.xzh.wms.dto.UploadDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
public class UploadService {

    @Value( "${upload.path}")
    private String path;

    @Value( "${upload.url}")
    private String url;

    public String upload(UploadDTO uploadDTO) {
        String name = uploadDTO.getName();
        String base64 = uploadDTO.getBase64();
        String[] array = StrUtil.splitToArray(base64, "base64,");
        byte[] bytes = Base64.decode(array[1]);
        name = System.currentTimeMillis()+"_"+name;
        FileUtil.writeBytes(bytes, path+ name);
        return url+name;
    }

    /**
     * 图库显示
     * @return
     */
    public List<FileInfoDTO> select() {
        List<FileInfoDTO> fileInfoDTOList = new ArrayList<>();

        File[] files = FileUtil.ls(path);

        ArrayList<String> suffixList = CollUtil.newArrayList("jpg", "png", "jpeg");
        //查看所有文件包括子文件下
        //files= FileUtil.loopFiles(path);
        Arrays.stream(files).forEach(file->{
            if (file.isFile()){
                String suffix = FileUtil.getSuffix(file);
                if (suffixList.contains(suffix)){
                    FileInfoDTO fileInfoDTO = new FileInfoDTO();
                    fileInfoDTO.setName(file.getName());
                    fileInfoDTO.setUrl(url+file.getName());
                    fileInfoDTOList.add(fileInfoDTO);
                }
            }
        });
        return fileInfoDTOList;
    }
}